import java.util.ArrayList;
import java.util.List;

import thoughtworks.test.InvalidRomanException;

public class code {

	public static List<Integer> valArr = new ArrayList<Integer>();

	public static void checkValidRomanString(String romanValue)
			throws InvalidRomanException {
		for (char letter : romanValue.toCharArray()) {
			if ("IVXLCDM".indexOf(letter) != -1) {
				valArr.add(ConstantsUtil.romanValues.get(new Character(letter)
						.toString()));
			} else {
				throw new InvalidRomanException("INVALID ROMAN NUMERAL.");
			}
		}
		for (String literal : ConstantsUtil.invalidCombinations) {
			if (romanValue.indexOf(literal) != -1) {
				throw new InvalidRomanException("INVALID ROMAN NUMERAL.");
			}
		}
	}

	public static void checkSubtractionRules(int a, int b)
			throws InvalidRomanException {
		if (b == ConstantsUtil.romanValues.get("V")
				|| b == ConstantsUtil.romanValues.get("L")
				|| b == ConstantsUtil.romanValues.get("D")) {
			throw new InvalidRomanException("INVALID ROMAN NUMERAL.");
		} else {
			if (!(a == (b * 5) || a == (b * 10)))
				throw new InvalidRomanException("INVALID ROMAN NUMERAL.");
		}
	}

	public static int convertRomanNumeral(String romanNumeral)
			throws InvalidRomanException {
		int numericValue = 0;
		try {
			for (int i = valArr.size() - 1; i >= 0; i--) {
				if (i != 0 && valArr.get(i) > valArr.get(i - 1)) {
					if (valArr.get(i) > valArr.get(i - 2)) {
						throw new InvalidRomanException("INVALID ROMAN NUMERAL.");
					} else {
						checkSubtractionRules(valArr.get(i), valArr.get(i - 1));
						numericValue += (valArr.get(i) - valArr.get(i-1));
						i--;
					}
				} else {
					numericValue += valArr.get(i);
				}
			}
			return numericValue;
		} catch (InvalidRomanException exception) {
			throw new InvalidRomanException(exception.getMessage());
		}
	}

	public static void main(String[] args) {
		String romanValue = "AMMCCCXXXIII";
		try {
			checkValidRomanString(romanValue);
			int a = convertRomanNumeral(romanValue);
			System.out.println(a);
		} catch (InvalidRomanException exception) {
			System.out.println(exception.getMessage());
		}
	}
}
